package com.zjs.jsp.ediorder.web;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjs.jsp.domain.config.WebHelpService;
import com.zjs.jsp.domain.jsp.Jsp_Order;
import com.zjs.jsp.ediorder.service.EncryptUtil;
import com.zjs.jsp.ediorder.service.MqProducer;
import com.zjs.jsp.ediorder.service.mongodb.EdiOrderRepository;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.rocketmq.client.producer.SendResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 订单接受
 *
 * @author 李文
 * @create 2017-08-29 18:50
 **/

@RestController
public class EdiOrderDataApiController
{

    private static final Logger LOGGER_FACTORY = LoggerFactory.getLogger(EdiOrderDataApiController.class);

    private static final ObjectMapper JSON = new ObjectMapper();


    @Autowired
    private EdiOrderRepository repository;

    @Autowired
    private MqProducer mqProducer;


    @Value("${deSkey}")
    private String deSkey;

    @Value("${orderkey:fales}")
    private String orderkey;

    @Value("${clientFlag}")
    private String clientFlag;


    @ApiOperation(value = "订单数据接收", notes = "接收  下发的订单数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "唯一标识", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "orders", value = "订单数据", required = true, dataType = "Jsp_Order", paramType = "body")
    })
    @PostMapping("/order/create/{uuid}")
    public String orderCreate(@PathVariable String uuid, @RequestBody Jsp_Order orders, HttpServletRequest request) {

        String data = create(orders, request, uuid);
        LOGGER_FACTORY.info(uuid + " 响应的数据是 " + data + "  " + WebHelpService.getParameterMap(request));
        return data;

    }


    private String create(Jsp_Order orders, HttpServletRequest request, String uuid) {
        // 转换成JSON
        String data;
        try {
            orders.setOuuid(uuid);
            data = JSON.writeValueAsString(orders);
            LOGGER_FACTORY.info(uuid + " 接受的数据是 " + data + "  " + WebHelpService.getParameterMap(request));
        } catch (Exception e) {
            LOGGER_FACTORY.error(uuid + "  订单数据转换异常 ", e);
            return WebHelpService.getString(50007, "接受数据无法格式化");
        }
        // 数据加密
        if (dataEnCode(orders, uuid)) {
            return WebHelpService.getString(40000, "数据加密异常");
        }

        // 保存数据
        String outData = saveData(orders, data, uuid);
        if (outData != null) {
            return outData;
        }

        try {
            data = JSON.writeValueAsString(orders);
        } catch (Exception e) {
            LOGGER_FACTORY.error(uuid + "  订单数据转换异常 ", e);
            return WebHelpService.getString(50007, "接受数据无法格式化");
        }

        // 发送数据到MQ
        if (sendMq(uuid, data)) {
            return WebHelpService.getString(40000, "转发数据失败");
        }
        return WebHelpService.getString(200, "接受成功");
    }

    private boolean dataEnCode(Jsp_Order o, String uuid) {
        try {
            EncryptUtil encryptUtil = new EncryptUtil(deSkey);
            o.setSra(encryptUtil.encode(o.getSra()));
            o.setSrn(encryptUtil.encode(o.getSrn()));
            o.setSrpp(encryptUtil.encode(o.getSrpp()));

        } catch (Exception e) {
            LOGGER_FACTORY.error(uuid + "数据加密异常 " + e.getMessage(), e);
            return true;
        }
        return false;
    }

    private boolean sendMq(String uuid, String data) {
        try {

            SendResult result = mqProducer.send(uuid, data);
            if (result == null) {
                // 发送MQ 失败
                LOGGER_FACTORY.error(uuid + "  发送MQ 失败 ");
                return true;
            }
        } catch (Exception e) {
            // 发送MQ 异常
            LOGGER_FACTORY.error(uuid + "  发送MQ异常 ", e);
            return true;
        }
        return false;
    }

    private String saveData(Jsp_Order orders, String log, String uuid) {
        try {
            repository.save(orders);
        } catch (DuplicateKeyException e) {
            return WebHelpService.getString(50001, "订单号重复提交");
        } catch (Exception e) {
            //   保存数据到 DB 失败
            LOGGER_FACTORY.error(uuid + "  保存数据到 DB 异常 " + e.getMessage(), e);
            return WebHelpService.getString(40000, "保存数据出错");
        }
        return null;
    }
}
